package com.suisung.shopsuite.agent.service;

import cn.hutool.core.lang.UUID;
import com.suisung.shopsuite.agent.componet.anwser.AiResponsePipeline;
import com.suisung.shopsuite.agent.componet.anwser.base.AiResponseHandlerChain;
import com.suisung.shopsuite.agent.componet.anwser.base.ResponseContext;
import com.suisung.shopsuite.agent.componet.message.ChatMessageManager;
import com.suisung.shopsuite.agent.configuration.rag.RagConfig;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.dashscope.QwenChatModel;
import dev.langchain4j.model.output.FinishReason;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.service.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ChatServiceIml implements ChatService {

    private final QwenChatModel qwenChatModel;

    private SystemMessage systemMessage;

    private final ChatMessageManager chatMessageManager;


    private final RagConfig.Assistant assistant;




    @Value("${ai.count}")
    private int COUNT;

    public void  init(){

        if(systemMessage == null)systemMessage = SystemMessage.systemMessage("你是一条小狗 无论主人说什么 你都只会汪汪汪 ");

    }


    @Override
    public void chat() {

    }

    @Override
    public AiMessage chat(String string) {
        Integer userId = getUserId();
        UserMessage userMessage = UserMessage.userMessage("abcd");
        chatMessageManager.SendRequest(userId,userMessage);
        Response<AiMessage> generate = qwenChatModel.generate(chatMessageManager.getRecentMessages(userId, COUNT));
        generate.finishReason();
        return generate.content();
    }

    @Override
    public AiMessage ChatByAssistant(Integer userId ,String string) {

        Result<String> answer = assistant.answer(string);
        AiResponsePipeline aiResponsePipeline = new AiResponsePipeline();
        aiResponsePipeline
                .addLast(this::handleStopReason)
                .addLast(this::handleToolExecution)
                .addLast(this::handleContentFilter)
                .addLast(this::handleLengthLimit)
                .addLast(this::handleOtherReasons);

        return null;
    }
    // 处理STOP状态
    private boolean handleStopReason(ResponseContext context, AiResponseHandlerChain chain) {
        if (FinishReason.STOP.equals(context.getFinishReason())) {
            context.setResult("正常结束: " + context.getAiResponse().content().text());
            return false; // 终止链式调用
        }
        chain.proceed(context); // 继续下一个处理器
        return true;
    }

    // 处理工具调用
    private boolean handleToolExecution(ResponseContext context, AiResponseHandlerChain chain) {
        if (FinishReason.TOOL_EXECUTION.equals(context.getFinishReason())) {
            // 执行工具调用逻辑
            String toolResult = executeTool(context.getAiResponse());
            context.setResult("工具执行结果: " + toolResult);
            return false;
        }
        chain.proceed(context);
        return true;
    }

    // 处理内容过滤
    private boolean handleContentFilter(ResponseContext context, AiResponseHandlerChain chain) {
        if (FinishReason.CONTENT_FILTER.equals(context.getFinishReason())) {
            context.setResult("内容被过滤: 不符合安全规范");
            return false;
        }
        chain.proceed(context);
        return true;
    }

    // 处理长度限制
    private boolean handleLengthLimit(ResponseContext context, AiResponseHandlerChain chain) {
        if (FinishReason.LENGTH.equals(context.getFinishReason())) {
            context.setResult("内容过长: 需要继续生成");
            // 可以在这里调用模型继续生成
            return false;
        }
        chain.proceed(context);
        return true;
    }

    // 处理其他情况
    private boolean handleOtherReasons(ResponseContext context, AiResponseHandlerChain chain) {
        context.setResult("其他情况: " + context.getFinishReason().name());
        return false;
    }

    // 工具执行逻辑
    private String executeTool(Response<AiMessage> response) {
        // 实际工具调用实现
        return "工具调用成功";
    }




    public Integer getUserId(){
        return (int) UUID.fastUUID().toString().hashCode();

    }
}
